package top.jfunc.token.mem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.jfunc.common.datetime.DatetimeUtils;
import top.jfunc.common.utils.CommonUtil;
import top.jfunc.token.TokenManager;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiongshiyan at 2021/5/13 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public class MemoryTokenManager<M>  implements TokenManager<M> {
    private static final Logger logger = LoggerFactory.getLogger(MemoryTokenManager.class);

    protected long apiExpires = 24*60*60;
    private Map<Object,Object> map = new ConcurrentHashMap<>();
    private String apiTokenPrefix="";

    @SuppressWarnings("unchecked")
    @Override
    public M findByToken(String token) {
        if(null == token){
            return null;
        }
        return (M)map.get(token);
    }

    @Override
    public String createToken(M m) {
        String token = getToken(m);
        saveToken(token, m);
        logger.info("createToken token = {} , m={}" , token , m.toString());
        return token;
    }

    @Override
    public boolean existByToken(String token) {
        return map.containsKey(token);
    }

    @Override
    public void updateExpires(String token) {
        if(null == token){
            return;
        }

        M m = findByToken(token);
        map.put(token, m);
    }

    @Override
    public String getToken(M m){
        return apiTokenPrefix + "-" + nowStr() + CommonUtil.randomString(16);
    }

    private String nowStr(){
        return DatetimeUtils.toStr(new Date() , DatetimeUtils.SDF_DATETIME_SHORT);
    }

    @Override
    public void saveToken(String token, M m) {
        if(null == token || null == m){
            return;
        }

        map.put(token, m);
    }

    @Override
    public boolean deleteToken(String token) {
        map.remove(token);
        return true;
    }

    @Override
    public void kickingOld(M m, String newToken) {
        throw new UnsupportedOperationException();
    }

    public long getApiExpires() {
        return apiExpires;
    }

    public void setApiExpires(long apiExpires) {
        this.apiExpires = apiExpires;
    }

    public String getApiTokenPrefix() {
        return apiTokenPrefix;
    }

    public void setApiTokenPrefix(String apiTokenPrefix) {
        this.apiTokenPrefix = apiTokenPrefix;
    }
}
